# URL: https://build.tarsier-infra.com/source/openEuler:22.09/mybatis/

import os, sys
import requests
from requests.adapters import HTTPAdapter
from bs4 import BeautifulSoup
import re

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + '../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'riscv_build_dataset.settings')

import django

django.setup()

from obs.models import obs_project, obs_package
from config import BASE_URL
from tqdm import tqdm

session = requests.Session()
session.mount('https://', HTTPAdapter(max_retries=5))
cookies = {
    '_obs_api_session': os.environ['OBS_COOKIE'],
}


def get_service_file(project_name: str, package_name: str):
    url = f'{BASE_URL}/source/{project_name}/{package_name}/_service'
    resp = session.get(url, cookies=cookies, timeout=2)

    # print(resp.text)
    soup = BeautifulSoup(resp.text, 'xml')
    params = soup.find('service').find_all('param')
    service = {}
    for param in params:
        # print(param.get('name'), param.text)
        service[param.get('name')] = param.text
    # print(service)
    return service


def get_git_repo(project_name: str, package_name: str):
    url = f'{BASE_URL}/source/{project_name}/{package_name}/_service'
    resp = session.get(url, cookies=cookies, timeout=2)

    # print(resp.text)
    # soup = BeautifulSoup(resp.text, 'lxml')
    # git_repo_url = soup.find_all('param', {'name': 'url'})
    git_repo_url = None
    try:
        git_repo_url = re.search(r'(http.*git)|(git.*git)', resp.text).group()
    except Exception as e:
        print('Git repo not found', file=sys.stderr)
    # print(git_repo_url)

    return git_repo_url


def clone_repo(repo_url: str, package_name: str):
    target_dir = f'../../clone_repo/{package_name}'
    if repo_url:
        if os.path.isdir(target_dir):
            # Dir exist
            os.chdir(target_dir)
            os.system('git pull')
        else:
            # Dir not exist
            os.system(f'git clone {repo_url} ../../clone_repo/{package_name}')


if __name__ == '__main__':
    # project_name = 'openEuler:23.09:BaseOS:01'
    project_name = os.environ.get('OBS_PROJECT')
    repository_name = os.environ.get('OBS_REPO')
    arch_name = os.environ.get('OBS_ARCH')

    # package_name = 'mpich'
    # get_service_file(project_name, package_name)
    # repo_url = get_git_repo(project_name, package_name)
    # clone_repo(repo_url, package_name)
    # exit(0)

    project = obs_project.objects.get(project_name=project_name)
    packages = obs_package.objects.filter(project=project)
    for package in tqdm(packages):
        # print(package.package_name)
        try:
            repo_url = get_git_repo(project_name, package.package_name)
            clone_repo(repo_url, package.package_name)
        except Exception as e:
            print(e, file=sys.stderr)
